<?php

declare(strict_types=1);

namespace ImiApp\ApiServer\Backend\Controller;

use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Phpben\Imi\Validate\Annotation\Validate;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
use Phpben\Imi\Auth\Annotation\Auth;

use Imi\Db\Db;

use ImiApp\ApiServer\Backend\Controller\CommonController as CommonController;

/**
 * @Auth(name="backend")
 * @Controller("/auction/")
 */
class AuctionController extends CommonController
{
    /**
     * @Inject("AuctionService")
     */
    protected $service;

    /**
     * @Action
     * @Route("read")
     * @return ResponseInterface
     */
    public function read(): ResponseInterface
    {
        return $this->response->success(null, $this->service->read() ?: []);
    }

    /**
     * @Action
     * @Route(url="create",method="POST")
     * @Validate
     * @param $data
     * @return ResponseInterface
     */
    public function create($data): ResponseInterface
    {
        return $this->service->create($data) ? $this->response->success('创建成功') : $this->response->error($this->service->getError());
    }

    /**
     * @Action
     * @Route(url="update",method="POST")
     * @Validate
     * @param $data
     * @return ResponseInterface
     */
    public function update($data): ResponseInterface
    {
        $预览区 = false;


        if (isset($data['apply_status']) && $data['apply_status'] != '1') {
            $auction = Db::name('auction')->where('id', '=', $data['id'])->find();
            //拍卖类型:1=贝壳竞拍,2=降价拍,3=升价拍,4=暗拍(降价拍),5=暗拍(升价拍)
            switch ($auction['type_status']) {
                case '1':
                    $拍卖类型 = '贝壳竞拍';
                    break;
                case '2':
                    $拍卖类型 = '降价拍';
                    break;
                case '3':
                    $拍卖类型 = '升价拍';
                    break;
                case '4':
                    $拍卖类型 = '暗拍(降价拍)';
                    break;
                case '5':
                    $拍卖类型 = '暗拍(升价拍)';
                    break;
                default:
                    # code...
                    break;
            }
            if ($auction['apply_status'] != $data['apply_status']) {
                switch ($auction['apply_status']) {
                    case '1':
                        if ($data['apply_status'] == '2') {
                            //通过 修改状态和时间

                            //switch type_status开始
                            switch ($auction['type_status']) {
                                case '1':
                                    $拍卖类型 = '贝壳竞拍';


                                    if ($auction['start_status'] == 'time') { //时间拍
                                        var_dump($auction['id'] . '贝壳拍卖多少秒后执行' . $auction['advance_show_s']);

                                        $data['start_time'] = time() + $auction['advance_show_s']; //预展示多少s
                                        $data['end_time'] = $data['start_time'] + $auction['end_s'];

                                        //使用那个对列    
                                        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                                        $message = new \Imi\Queue\Model\Message;
                                        //发布对列
                                        $message->setMessage(json_encode(['type' => 'update_auction_status' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                                        $queue->push($message, (float)$auction['advance_show_s']);

                                        $预览区 = true;
                                    }

                                    $data['status'] = '2'; //状态:1=待展示,2=预展示,3=进行中,5=结束,6=已下架
                                    $data['updatetime'] = time();

                                    break;
                                case '2':
                                    $拍卖类型 = '降价拍';
                                    $id = $data['id'];
                                    if ($auction['start_status'] == 'time') { //时间拍
                                        var_dump($auction['id'] . '降价拍多少秒后执行' . $auction['advance_show_s']);

                                        $data['start_time'] = time() + $auction['advance_show_s']; //预展示多少s
                                        $data['end_time'] = $data['start_time'] + $auction['end_s'];
                                        //使用那个对列    
                                        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                                        $message = new \Imi\Queue\Model\Message;
                                        //发布对列
                                        $message->setMessage(json_encode(['type' => 'update_auction_status' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                                        $queue->push($message, (float)$auction['advance_show_s']);

                                        $预览区 = true;
                                    }
                                    $data['status'] = '2'; //状态:1=待展示,2=预展示,3=进行中,5=结束,6=已下架
                                    $data['updatetime'] = time();
                                   
                                    break;
                                case '3':
                                    $拍卖类型 = '升价拍';
                                    $id = $data['id'];
                                    //定时器 多少秒后更新状态
                                    // 只执行一次 1 秒后执行一次

                                    // $timerId3 = \Imi\Timer\Timer::after(20000, function() use($拍卖类型,$id){
                                    //     var_dump($拍卖类型.$id.'测试开始进行'.date('Y-m-d H:i:s'));
                                    //     $res = Db::name('auction')->where('id','=',$id)->update(['updatetime'=>time()]);
                                    //     var_dump($拍卖类型.$id.'测试更新成功'.date('Y-m-d H:i:s'));
                                    // });



                                    // //使用那个对列    
                                    // $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                                    // $message = new \Imi\Queue\Model\Message;
                                    // //发布对列
                                    // $message->setMessage(json_encode(['type'=>'update_auction_status'.$auction['type_status'],'data'=>$auction],JSON_UNESCAPED_UNICODE));
                                    // $queue->push($message,15);



                                    if ($auction['start_status'] == 'time') { //时间拍
                                        var_dump($auction['id'] . '升价拍多少秒后执行' . $auction['advance_show_s']);

                                        $data['start_time'] = time() + $auction['advance_show_s']; //预展示多少s
                                        $data['end_time'] = $data['start_time'] + $auction['end_s'];

                                        //使用那个对列    
                                        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                                        $message = new \Imi\Queue\Model\Message;
                                        //发布对列
                                        $message->setMessage(json_encode(['type' => 'update_auction_status' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                                        $queue->push($message, (float)$auction['advance_show_s']);



                                        $预览区 = true;

                                        // $timerId2 = \Imi\Timer\Timer::after((int)($auction['advance_show_s'])*1000, function() use($拍卖类型,$id){
                                        //     var_dump($拍卖类型.$id.'开始进行'.date('Y-m-d H:i:s'));
                                        //     $res = Db::name('auction')->where('id','=',$id)->where('status','=','2')->update(['status'=>'3','updatetime'=>time()]);
                                        //     var_dump($拍卖类型.$id.'更新成功'.date('Y-m-d H:i:s'));
                                        // });

                                    }

                                    // if ($auction['start_status'] == 'number') { //人数
                                    //     //只是修改展示,开始以人数满后开始

                                    //     //结束时间对列
                                    //     //使用那个对列    
                                    //     $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                                    //     $message = new \Imi\Queue\Model\Message;
                                    //     //发布对列
                                    //     $message->setMessage(json_encode(['type' => 'auction_finish3' , 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                                    //     $queue->push($message, (float)$auction['end_s']);
                                    // }


                                    $data['status'] = '2'; //状态:1=待展示,2=预展示,3=进行中,5=结束,6=已下架

                                    $data['updatetime'] = time();

                                    break;
                                case '4':
                                    $拍卖类型 = '暗拍(降价拍)';

                                    if ($auction['start_status'] == 'time') { //时间拍
                                        var_dump($auction['id'] . '暗拍(降价拍)多少秒后执行' . $auction['advance_show_s']);

                                        $data['start_time'] = time() + $auction['advance_show_s']; //预展示多少s
                                        $data['end_time'] = $data['start_time'] + $auction['end_s'];

                                        //使用那个对列    
                                        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                                        $message = new \Imi\Queue\Model\Message;
                                        //发布对列
                                        $message->setMessage(json_encode(['type' => 'update_auction_status' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                                        $queue->push($message, (float)$auction['advance_show_s']);

                                        $预览区 = true;
                                    }

                                    $data['status'] = '2'; //状态:1=待展示,2=预展示,3=进行中,5=结束,6=已下架
                                    $data['updatetime'] = time();

                                    break;
                                case '5':
                                    $拍卖类型 = '暗拍(升价拍)';



                                    if ($auction['start_status'] == 'time') { //时间拍
                                        var_dump($auction['id'] . '暗拍(升价拍)多少秒后执行' . $auction['advance_show_s']);

                                        $data['start_time'] = time() + $auction['advance_show_s']; //预展示多少s
                                        $data['end_time'] = $data['start_time'] + $auction['end_s'];

                                        //使用那个对列    
                                        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                                        $message = new \Imi\Queue\Model\Message;
                                        //发布对列
                                        $message->setMessage(json_encode(['type' => 'update_auction_status' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                                        $queue->push($message, (float)$auction['advance_show_s']);

                                        $预览区 = true;
                                    }

                                    $data['status'] = '2'; //状态:1=待展示,2=预展示,3=进行中,5=结束,6=已下架
                                    $data['updatetime'] = time();

                                    break;
                                default:
                                    # code...
                                    break;
                            } //switch type_status结束




                        }
                        if ($data['apply_status'] == '3') {
                            //拒绝 退回库存


                            $this->解冻库存($auction,$拍卖类型);


                            $act_surety = Db::name('store_surety_log')->where('type_status', '=', 'act_surety')->where('public_id', '=', $data['id'])->where('status', '=', '1')->where('type', '=', $拍卖类型)->value('act_surety');
                            if (!$act_surety) {
                                $act_surety =  $data['buyer_surety'] * config('auction_surety_multiple');
                            }
                            $tpmecms = new \ImiApp\ApiServer\Api\Controller\Tpmecms;
                            //解冻店铺的活动保证金
                            $tpmecms->IncStoreSurety($auction['store_id'], $act_surety, '拒绝' . $拍卖类型 . '活动,解冻保证金', $拍卖类型, $data['id'], 'act_surety');
                            $tpmecms->UnFreezeStore($auction['store_id'], 'act_surety', 'store_auction', $data['id'], '拒绝' . $拍卖类型 . '活动,解冻保证金');
                        }

                        break;


                    default:
                        return $this->error('操作后无法修改');
                        break;
                }
            }
        }

        if ($预览区) {
            //推送到拍卖群组里面信息 可以公共
            $推送信息 = ['auction_id' => $auction['id'], 'type_status' => $auction['type_status']];
            $tpmecms = new \ImiApp\ApiServer\Api\Controller\Tpmecms;
            $ToGroup_data = $tpmecms->ws_success('拍卖预览', $推送信息, 'auction_show');
            \Imi\Server\Server::sendToGroup('auction_' . $auction['id'], $ToGroup_data, 'main');
            \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据
        }


        return $this->service->update($data) ? $this->response->success('更新成功') : $this->response->error($this->service->getError());
    }



    public function 解冻库存($auction,$拍卖类型)
    {
        //退回库存
        if ($auction['stock_status'] == 'freeze') {
            $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
            foreach ($goods_sku_price_arr as $key => $sku_id) {
                $this->IncGoodsStock($sku_id, 1, '拒绝' . $拍卖类型 . '活动,增加库存', $auction['id']);
            }
            Db::name('auction')->where('id', '=', $auction['id'])->update(['stock_status' => 'unfreeze']);
        }
    }



    /**
     * 增加商品库存
     *
     * @param int $goods_sku_price_id 商品价格id
     * @param integer $num 数量默认1
     * @param string $ps 库存备注
     * @param int $order_id 订单id
     * @return void 
     */
    protected function IncGoodsStock($goods_sku_price_id, $num = 1, $ps = null, $order_id = null)
    {
        Db::name('goodssku_price')->where('id', '=', $goods_sku_price_id)->setFieldInc('stock', $num)->update();
        $data['status'] = '2'; //状态:1=减库存,2=加库存
        $data['ps'] = $ps;
        $data['num'] = $num;
        $data['order_id'] = $order_id;
        $data['goods_sku_price_id'] = $goods_sku_price_id;
        $data['time'] = time();
        $data['after'] =   Db::name('goodssku_price')->where('id', '=', $goods_sku_price_id)->value('stock');
        Db::name('goods_stock_log')->insert($data);
    }


    /**
     * @Action
     * @Route(url="delete",method="POST")
     * @return ResponseInterface
     */
    public function delete(): ResponseInterface
    {
        return $this->service->delete() ? $this->response->success('删除成功') : $this->response->error($this->service->getError());
    }

    /**
     * @Action
     * @Route(url="operate",method="POST")
     * @return ResponseInterface
     */
    public function operate(): ResponseInterface
    {
        return $this->service->operate() ? $this->response->success('操作成功') : $this->response->error($this->service->getError());
    }
}
